package com.qf.mybatis;

import com.qf.dao.UserDao;
import com.qf.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 *  Maven的约定大于配置
 *    src/main/java   ***.java
 *    src/main/resources  **.properties   **.xml ...
 *    test/java/ 测试
 *
 * 测试Mybatis连接Mysql数据库
 *  CRUD
 *  添加
 *  修改
 *  删除
 *  查询
 * @author lixu
 */
public class MybatisTest2 {


    //声明
    private SqlSessionFactory sqlSessionFactory;

    //全局  给所有方法使用
    @Before
    public void testBefore() throws Exception{
        //1:由Mybatis读取mybatis-config.xml 核心配置文件
        //File file = Resources.getResourceAsFile("mybatis-config.xml");
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        //工厂模式 ： 23种设计模式
        //2:构造工厂
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);

    }


    /**
     * 复杂查询
     * select * from t_users where name like %%  and birthday = new Date() and sex = 男 limit 开始行,每页数
     * select count(1) from t_users
     */
    @Test
    public void testSelect() throws Exception{
        //3:生产连接 Mysql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //4:发送SQL语句  添加
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        String name = "明";
        String sex = "男";

        List<User> userList = userDao.findUserListByNameAndSex(name,sex);
        for (User user : userList) {
            System.out.println(user);
        }
        //关闭
        sqlSession.close();
    }
    /**
     * 模糊查询
     */
    @Test
    public void testSelectLike() throws Exception{
        //3:生产连接 Mysql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //4:发送SQL语句  添加
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        String name = "明";
        List<User> userList = userDao.findUserListByNameLike(name);
        for (User user : userList) {
            System.out.println(user);
        }
        //关闭
        sqlSession.close();
    }

    /**
     * 添加  主键回填
     */
    @Test
    public void testAddReturnId() throws Exception{
        //3:生产连接 Mysql
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //4:发送SQL语句  添加
        UserDao userDao = sqlSession.getMapper(UserDao.class);


        User user = new User();
        user.setName("明");//模糊
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR,-1);
        user.setSex("女");
        user.setPassword("123456");
        user.setRegistTime(new Date());

        //保存
        userDao.insertUserReturnId(user);

        System.out.println("保存成功之后ID回填:" + user.getId());

        sqlSession.commit();
        //关闭
        sqlSession.close();
    }
}
